package me.xingyannian.zhaopin.controller;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import me.xingyannian.zhaopin.dto.PreExamineeDto;
import me.xingyannian.zhaopin.entity.ChangCi;
import me.xingyannian.zhaopin.entity.PreExaminee;
import me.xingyannian.zhaopin.listener.PreExamineeDtoListener;
import me.xingyannian.zhaopin.service.ChangCiService;
import me.xingyannian.zhaopin.service.PreExamineeService;
import me.xingyannian.zhaopin.service.QualityUniversityService;
import me.xingyannian.zhaopin.vo.PreExamineeVo;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * PreExamineeController
 *
 * @author XING&WANG
 * @version 2025/05/05 13:08
 **/
@Controller
@RequestMapping("/preExaminee")
public class PreExamineeController {
    private final PreExamineeService preExamineeService;
    private final ChangCiService changCiService;
    private final QualityUniversityService qualityUniversityService;

    public PreExamineeController(PreExamineeService preExamineeService, ChangCiService changCiService, QualityUniversityService qualityUniversityService) {
        this.preExamineeService = preExamineeService;
        this.changCiService = changCiService;
        this.qualityUniversityService = qualityUniversityService;
    }
    // list
    @RequestMapping("/list")
    public String list(Model model, @RequestParam(value = "page", defaultValue = "1") int page
            , @RequestParam Integer changCiId) {
        // 设置默认值
        int pageNum = page - 1;
        // pageNum最小为0
        if (pageNum < 0) {
            pageNum = 0;
        }
        int pageSize = 10;
        //System.out.println("pageNum: " + pageNum + "changCiId: " + changCiId);
        var option = this.changCiService.findById(changCiId.longValue());
        if (option.isEmpty()) {
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "不存在的招聘批次");
            return "preExaminee/list";
        }
        ChangCi changCi = option.get();
        model.addAttribute("error", false);
        model.addAttribute("changCi", changCi);
        Page<PreExaminee> preExaminees = preExamineeService.findAllByChangCi(changCi, pageNum, pageSize);
        model.addAttribute("preExaminees", preExaminees.getContent());
        // Page从0开始，前端从1开始，所以要加1
        model.addAttribute("currentPage", preExaminees.getNumber() + 1);
        model.addAttribute("totalPages", preExaminees.getTotalPages());
        return "preExaminee/list";
    }
    // download 模板  http://localhost:8080/preExaminee/download
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("预报名考生导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), PreExamineeVo.class).sheet("1").doWrite(new ArrayList<>());
    }
    // import
    @GetMapping("/import")
    public String importExcel(Model model, @RequestParam Integer changCiId) {
        var option = this.changCiService.findById(changCiId.longValue());
        if (option.isEmpty()) {
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "不存在的招聘批次");
        }else{
            model.addAttribute("error", false);
            model.addAttribute("changCi", option.get());
        }
        return "preExaminee/import";
    }
    @PostMapping("/import")
    public String importExcel(Model model, @RequestParam Integer changCiId, @RequestParam("file") MultipartFile file) {
        var option = this.changCiService.findById(changCiId.longValue());
        if (option.isEmpty()) {
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "不存在的招聘批次");
            return "preExaminee/import";
        }
        var changCi = option.get();
        model.addAttribute("changCi", changCi);
        if (file.isEmpty()) {
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "请选择要上传的文件");
            return "preExaminee/import";
        }
        // 获取上传文件名
        String fileName = file.getOriginalFilename();
        // 验证文件类型
        if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
            System.out.println("文件类型错误");
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "只支持Excel文件(.xlsx或.xls)");
            return "preExaminee/import";
        }
        try {
            // 这里可以添加Excel文件解析逻辑
            // 示例：使用EasyExcel读取文件内容
            EasyExcel.read(file.getInputStream(), PreExamineeDto.class, new PreExamineeDtoListener(preExamineeService, qualityUniversityService, changCi)).sheet("1").doRead();
            // 暂时只返回成功消息
            model.addAttribute("error", false);
            model.addAttribute("successMsg", "文件上传成功: " + fileName);
            return "redirect:/preExaminee/list?changCiId=" + changCiId;
        }
        catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "文件处理失败: " + e.getMessage());
            return "preExaminee/import";
        }
    }
    // add
    // edit
    // delete
    @GetMapping("/delete")
    public String delete(@RequestParam Integer changCiId, Model model) {
        var option = this.changCiService.findById(changCiId.longValue());
        if (option.isEmpty()) {
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "不存在的招聘批次");
            return "error";
        }
        var changCi = option.get();
        this.preExamineeService.deleteAllByChangCi(changCi);
        return "redirect:/preExaminee/list?changCiId=" + changCiId;
    }
    // Attribute matching
    @GetMapping("/schoolMatch")
    public String schoolMatch(@RequestParam Integer changCiId, Model model) {
        var option = this.changCiService.findById(changCiId.longValue());
        if (option.isEmpty()) {
            model.addAttribute("error", true);
            model.addAttribute("errorMsg", "不存在的招聘批次");
            return "error";
        }
        var changCi = option.get();
        this.preExamineeService.schoolMatch(changCi);
        return "redirect:/preExaminee/list?changCiId=" + changCiId;
    }
}
